//
//  UITextView+Emoticon.swift
//  表情键盘
//
//  Created by zhangguo on 15/10/20.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit


extension UITextView {
    
    func insertEmoticon(emoticon:Emoticon){
        //传输emoji
        if emoticon.emoji != nil{
            
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            
            return
        }
        
        //插入图片文字
        if emoticon.chs != nil {
            //创建图片属性字符串
            let attchment = EmoticonAttachment()
            
            attchment.chs  = emoticon.chs
            
            attchment.image = UIImage(contentsOfFile: emoticon.imagePath)
            //设置边界
            let h = font!.lineHeight
            attchment.bounds = CGRect(x: 0, y: -4, width: h, height: h)
            
            let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attchment))
            
            imageText.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1))
            
            //获取可变的属性文本
            let attrString = NSMutableAttributedString(attributedString: attributedText)
            //插入图片文字
            attrString.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
            
            //3,使用可变属性文本替换文本视图的
            
            //4,恢复光标位置
            let range = selectedRange
            attributedText = attrString
            
            selectedRange = NSRange(location: range.location + 1, length: 0)
            
        }
    }

    
    
    //对属性文本进行检测。并且拼接返回一个字符串
    var emoticonText: String{
        
            //属性文本是分段保存的，能否把每一个分段拿到
        let attrString = attributedText
        var strM = String()
        
        attrString.enumerateAttributesInRange(NSMakeRange(0, attrString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)){ (dict, range,_)  in
            
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                strM += attachment.chs!
                
            }else{
                
                //使用range获取文本内容
                let str = (attrString.string as NSString).substringWithRange(range)
                strM += str
            }
        
        }
       return strM
    }
    
}
